<script setup>
import { use } from 'echarts/core'
import { BarChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { ref, watch } from 'vue'

use([BarChart, TitleComponent, TooltipComponent, GridComponent, LegendComponent])

const props = defineProps({
  data: {
    type: Object,
    required: true
  },
  title: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '400px'
  }
})

const option = ref({
  title: {
    text: props.title,
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01]
  },
  yAxis: {
    type: 'category',
    data: props.data.categories
  },
  series: [
    {
      name: '商品数量',
      type: 'bar',
      data: props.data.counts,
      itemStyle: {
        color: '#5470C6'
      },
      label: {
        show: true,
        position: 'right'
      }
    }
  ]
})

watch(() => props.data, (newVal) => {
  option.value.yAxis.data = newVal.categories
  option.value.series[0].data = newVal.counts
}, { deep: true })

watch(() => props.title, (newVal) => {
  option.value.title.text = newVal
})
</script>

<template>
  <v-chart class="chart" :option="option" :style="{ height }" />
</template>

<style scoped>
.chart {
  width: 100%;
}
</style>